from keras import losses
import matplotlib.pyplot as plt
from keras import metrics
from keras import layers
from keras import optimizers
from keras import models
import numpy as np
from keras.datasets import imdb
(train_data, train_labels), (test_data,
                             test_labels) = imdb.load_data(num_words=10000)
word_index = imdb.get_word_index()
reverse_word = dict([(value, key) for (key, value) in word_index.items()])

# reverse_word
decode_view = ' '.join([reverse_word.get(i-3, '') for i in train_data[0]])
# 将评论解码。注意，索引减去了 3，因为 0、1、2 为“padding”(填充)、“start of sequence”(序列开始)、“unknown”(未知词)分别保留的索引


def vectorize(sequences, dimension=10000):
    # 创建一个（len（sequence），10000）的向量，句子数量*单词序列 有这个单词该值为1
    result = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        result[i, sequence] = 1
    return result


x_train = vectorize(train_data)
x_test = vectorize(test_data)

y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

x_val = x_train[:10000]
partial_x = x_train[10000:]
y_val = y_train[:10000]
partial_y = y_train[10000:]


model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.summary()

model.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy,
              metrics=[metrics.binary_accuracy])

history = model.fit(partial_x, partial_y, epochs=5,
                    batch_size=512, validation_data=(x_test, y_test))
history_dict = history.history
print(history_dict.keys())
# 绘制训练损失和验证损失
acc = history_dict['binary_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
val_acc = history_dict['val_binary_accuracy']
epochs = range(1, len(acc)+1)
plt.plot(epochs, acc, label='acc')
# plt.plot(epochs,loss,label='loss')
plt.plot(epochs, val_acc, label='val_acc')
# plt.plot(epochs,val_loss,label='val_loss')
plt.xlabel('Epochs')
plt.ylabel('acc')
plt.legend()
plt.show()


results = model.evaluate(x_test, y_test)
print(results)
y_pred = model.predict(x_test)